package com.agileai.pm.module.base.handler;


 import java.util.Date;
import java.util.List;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.agileai.common.KeyGenerator;
import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.annotation.PageAction;
import com.agileai.hotweb.controller.core.StandardEditHandler;
import com.agileai.hotweb.domain.FormSelectFactory;
import com.agileai.hotweb.domain.core.User;
import com.agileai.hotweb.renders.AjaxRenderer;
import com.agileai.hotweb.renders.LocalRenderer;
import com.agileai.hotweb.renders.RedirectRenderer;
import com.agileai.hotweb.renders.ViewRenderer;
import com.agileai.pm.cxmodule.ProcPlanAdminManage;
import com.agileai.pm.cxmodule.ProjectInfoManage;
import com.agileai.pm.domain.Consts;
import com.agileai.pm.domain.Project;
import com.agileai.pm.module.base.service.ProjectReportManage;
import com.agileai.util.DateUtil;
import com.agileai.util.MapUtil;
import com.agileai.util.StringUtil;

public class ProjectInfoManageEditHandler
        extends StandardEditHandler {
    public ProjectInfoManageEditHandler() {
        super();
        this.listHandlerClass = ProjectInfoManageListHandler.class;
        this.serviceId = buildServiceId(ProjectInfoManage.class);
    }

    public ViewRenderer prepareDisplay(DataParam param) {
		String operaType = param.get(OperaType.KEY);
		if (isReqRecordOperaType(operaType)||StringUtil.isNullOrEmpty(operaType)){
			Project project = (Project)this.getSessionAttribute(Consts.ProjectSessionKey);
		    String projectId = project.getProjectId();
		    String projectIdDef = param.stringValue("PI_ID");
		    if(StringUtil.isNotNullNotEmpty(projectIdDef)){
		    	projectId = projectIdDef;
		    }
		    param.put("PI_ID", projectId);
		    if(StringUtil.isNullOrEmpty(projectId)){
		    	param.put("PI_ID", "N");
		    }
			DataRow record = getService().getRecord(param);
			if(!MapUtil.isNullOrEmpty(record)){
				Date date = (Date) record.get("PI_CREATE_TIME");
				String createTime = DateUtil.format(DateUtil.YYMMDDHHMISS_HORIZONTAL, date);
				record.put("PI_CREATE_TIME",createTime);
			try{
				String emailJsonStr = record.stringValue("PI_MAIL_CONFIGURE");
				if(StringUtil.isNotNullNotEmpty(emailJsonStr)){
					JSONObject emailJson = new JSONObject(emailJsonStr);
					record.put("PI_MAIL_SEVER", emailJson.get("emailServer"));
					record.put("PI_MAIL_POST",  emailJson.get("emailPost"));
					record.put("PI_MAIL_PWD",  emailJson.get("emailPassWord"));
					record.put("EMAIL_TEMPLATE",  emailJson.get("emailTemplate"));
				}
			}catch(JSONException e) {
				e.printStackTrace();
			}
				String type = record.getString("PI_TYPE");
				param.put("PI_TYPE",type);
				param.merge(record.toDataParam());
			}
			this.setAttributes(record);	
		}else if("insert".equals(operaType)){
			String time = DateUtil.format(DateUtil.YYMMDDHHMI_HORIZONTAL, new Date());
			param.put("PI_CREATE_TIME",time);
			User user = (User)this.getUser();
			String userName = user.getUserName();
			param.put("PI_CREATE_PEOPLE_NAME",userName);
			param.put("PI_CREATE_PEOPLE",user.getUserId());
		}
		this.setOperaType(operaType);
		this.setAttributes(param);
		processPageAttributes(param);
		String backHidden = param.getString("backHidden");
		if(StringUtil.isNullOrEmpty(backHidden)){
			this.setAttribute("backHidden", "no");
		}
		return new LocalRenderer(getPage());
	}
    
    protected void processPageAttributes(DataParam param) {
    	   setAttribute("PI_TYPE",
                   FormSelectFactory.create("PI_TYPE")
                                    .addSelectedValue(getOperaAttributeValue("PI_TYPE",
                                                                             "IntegratedDev")));
    }
    @PageAction
	public ViewRenderer buildProjectCode(DataParam param){
    	String operaType = param.get(OperaType.KEY);
    	String strNum = getService().getProjectNumRecord();
    	String piCode ="";
    	if(OperaType.CREATE.equals(operaType)){
    		piCode = strNum;
    	}else{
    		piCode = param.get("PI_CODE");
    	}
    	return new AjaxRenderer(piCode);
    }
    protected ProjectInfoManage getService() {
        return (ProjectInfoManage) this.lookupService(this.getServiceId());
    }
    
    protected void createReport(DataRow row,String projectId ){
        ProjectReportManage reporMangerService = this.lookupService(ProjectReportManage.class);
    	DataParam reportInfoParam = new DataParam();
		reportInfoParam.put("PI_ID", projectId);
		reportInfoParam.put("PR_NAME", row.stringValue("USER_NAME"));
		reportInfoParam.put("PR_SEX", row.stringValue("USER_SEX"));
		reportInfoParam.put("PR_POST", row.stringValue("PR_POST"));
		reportInfoParam.put("PR_MAIL", row.stringValue("USER_MAIL"));
		reportInfoParam.put("PR_PHONE", row.stringValue("USER_PHONE"));
		reportInfoParam.put("PR_SORT", row.stringValue("PR_SORT"));
		reporMangerService.createRecord(reportInfoParam);
    }

	public ViewRenderer doSaveAction(DataParam param){
		String operateType = param.get(OperaType.KEY);
		String emailServer = param.stringValue("PI_MAIL_SEVER");
		String emailPost = param.stringValue("PI_MAIL_POST");
		String emailPassWord = param.stringValue("PI_MAIL_PWD");
		String emailTemplate = param.stringValue("EMAIL_TEMPLATE");
		JSONObject jsonObj = new JSONObject();
		User user = (User) this.getUser();
		try {
			jsonObj.put("emailServer", emailServer);
			jsonObj.put("emailPost", emailPost);
			jsonObj.put("emailPassWord", emailPassWord);
			jsonObj.put("emailTemplate", emailTemplate);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		param.put("PI_MAIL_CONFIGURE", jsonObj.toString());
		if (OperaType.CREATE.equals(operateType)){
			String sgId = KeyGenerator.instance().genKey();
			String files = "系统配置,联系名单,会议纪要,变更管理,需求管理,设计文档,标准规范,测试文档,部署文档,问题记录,升级记录,使用手册,维护手册,验收文档";
			String[] array = files.split(",");
			for (int i = 0; i < array.length; i++) {
				String file = array[i];
				param.put("PI_ID",sgId);
				param.put("PD_ID", KeyGenerator.instance().genKey());
				param.put("PD_NAME",file);
				param.put("PD_SORT",i);
				getService().insertFileManage(param);
			}
			String piName = param.get("PI_NAME");
			String PPA_NAME = piName+"整体计划";
			param.put("PPA_ID",sgId);
			param.put("PI_ID",sgId);
			param.put("PPA_NAME",PPA_NAME);
			getService().insertPlanInfo(param);
			ProcPlanAdminManage planService = this.lookupService(ProcPlanAdminManage.class);
			String[] groupNames = {"需求分析","功能设计","开发测试","业务联测","系统上线"};
			for(int i = 0;i < groupNames.length;i++){
				String taskPlanKey = KeyGenerator.instance().genKey();
				DataParam temParam = new DataParam();
				temParam.put("PI_ID", sgId);
				temParam.put("PPA_PID", sgId);
				temParam.put("PPA_NAME", groupNames[i]);
				temParam.put("PPA_TYPE", "GROUP");
				temParam.put("PPA_CREATE", user.getUserId());
				temParam.put("PPA_CREATE_TIME", new Date());
				temParam.put("PPA_SORT",String.valueOf(i));
				planService.createRecord(temParam, taskPlanKey);
				temParam.put("PPA_SORT","");
				temParam.put("PPA_NAME", "样例");
				temParam.put("PPA_TYPE", "TASK");
				temParam.put("PPA_STATE", "NOTSTART");
				temParam.put("PPA_PID", taskPlanKey);
				temParam.put("PPA_SORT","10");
				temParam.put("PPA_WORK_DAY",(float)1);
				planService.createRecord(temParam);
			}
			String userId = user.getUserId(); 
			String piManager =param.getString("PI_MANAGER");
			String [] masters = new String[]{userId,piManager};
			String[] post = {"PROJECTMASTER","MANAGER"};
			List<DataRow> findUserType = getService().findUserType(userId,piManager);
			String master ="Inside";
			String manager ="Inside";
			for(int i = 0; i < findUserType.size(); i++){
				DataRow row = findUserType.get(i);
				String userType = row.getString("USER_TYPE");
				if("PROJECTMASTER".equals(row.getString("PP_POST")) && !StringUtil.isNullOrEmpty(userType)){
					master = userType;
				}
				if("MANAGER".equals(row.getString("PP_POST")) && !StringUtil.isNullOrEmpty(userType)){
					manager = userType;
				}
			}
			String[] type = {master,manager};
			for(int i = 0; i < 2; i++ ){
				String ppId = KeyGenerator.instance().genKey();
				int sort = getService().getMaxSort(param);
				String masterId = masters[i];
				param.put("PP_ID",ppId);
				param.put("USER_ID",masterId);
				param.put("PP_SORT",sort);
				param.put("PP_POST", post[i]);
				param.put("USER_TYPE", type[i]);
				getService().insertPeopleInfo(param);
				getService().updateUserType(param);
			}
			getService().createRecord(param);
			DataRow masterInfo = getService().getUserInfo(param.stringValue("PI_CREATE_PEOPLE"));
			masterInfo.put("PR_POST", "项目总监");
			masterInfo.put("PR_SORT", 50);
			DataRow managerInfo = getService().getUserInfo(param.stringValue("PI_MANAGER"));
			managerInfo.put("PR_POST", "项目经理");
			managerInfo.put("PR_SORT", 60);
			this.createReport(masterInfo, sgId);
			this.createReport(managerInfo, sgId);
		}
		else if (OperaType.UPDATE.equals(operateType)){
			getService().updateRecord(param);	
		}
		return new RedirectRenderer(getHandlerURL(listHandlerClass));
	}
	
	@PageAction
	public ViewRenderer saveEmailConfig(DataParam param){
		String responseText = "";
		String projectId = param.stringValue("PI_ID");
		String emailServer = param.stringValue("PI_MAIL_SEVER");
		String emailPost = param.stringValue("PI_MAIL_POST");
		String emailPassWord = param.stringValue("PI_MAIL_PWD");
		String emailTemplate = param.stringValue("EMAIL_TEMPLATE");
		JSONObject jsonObj = new JSONObject();
		try {
			jsonObj.put("emailServer", emailServer);
			jsonObj.put("emailPost", emailPost);
			jsonObj.put("emailPassWord", emailPassWord);
			jsonObj.put("emailTemplate", emailTemplate);
			
		} catch (JSONException e) {
			e.printStackTrace();
		}
		DataParam emailconfigParam = new DataParam();
		emailconfigParam.put("PI_ID", projectId);
		emailconfigParam.put("PI_MAIL_CONFIGURE", jsonObj.toString());
		this.getService().updateConfigInfo(emailconfigParam);
		return new AjaxRenderer(responseText);
	}
}
